package com.dragon.cloud.zconf.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.utils.PathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


public class ZConfNodeUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZConfNodeUtil.class);

    public static boolean legalNodePath(String nodePath) {
        try {
            PathUtils.validatePath(nodePath);

            Pattern pattern = Pattern.compile("/{2,}");
            Matcher matcher = pattern.matcher(nodePath);
            Pattern pattern1 = Pattern.compile("[\\\\`~!@#$%^&*()]");
            Matcher matcher1 = pattern1.matcher(nodePath);

            return StringUtils.isNotEmpty(nodePath) && nodePath.contains("/") && !nodePath.endsWith("/") &&
                !matcher.find() && !matcher1.find();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return false;

    }

    /**
     * 例如 ：@{/zconf/product} 返回2
     * 
     * @param nodePath
     * @return
     */
    public static int getPathLevel(String nodePath) {
        int index = -1;
        int i = 0;
        if (legalNodePath(nodePath)) {
            while (true) {
                index = nodePath.indexOf("/", index + 1);
                if (index != -1) {
                    i++;
                } else {
                    break;
                }
            }
        }
        return i;
    }

    public static String getPathName(String nodePath) {
        String pathName = null;
        if (legalNodePath(nodePath)) {
            pathName = nodePath.substring(nodePath.lastIndexOf("/") + 1);
        }
        return pathName;
    }

    public static String StringFilter(String str) throws PatternSyntaxException {
        Pattern p = Pattern.compile("[`~!@#$%^&*()+=|{}':;',<>?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]");
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static void main(String[] args) {
        System.out.println(legalNodePath("/zconf/product/fsdfsd/"));
        System.out.println("abc".substring(0, 3));
        System.out.println("abc".charAt(1) == 'a');
    }

}
